from math import exp, log10
import scipy.stats
from scipy.integrate import inf
from numpy import isnan

def factorial(n):
	if n < 2:
		return 1
	else:	
		return reduce(lambda x, y: x * y, range(1, n + 1))

def poisson(l, k, s):
	d = scipy.stats.poisson(l)
	p = d.pmf(l - k)
#	p = scipy.stats.poisson(l).pmf(l,l-k)
#	p = d.cdf(k).tolist()
#	p = d.sf(k).tolist()
	if isnan(p):
		p = 1
#	if p > 0.5: p = 1 - p
	return p

def poissonParameters(sp, mz, tol = 0.5, u = 'Da'):
	""" return the mean and number of occourences
	for a poisson distribution
	"""
	
	Lambda = 0			# expected value, lambda
	Kappa = 0			# number of ions that match, can be 1 or 0
	found = []

	found =  sp.closeTo(mz, tol, u).peakMasses()	# get masses of peaks near to this ion

	Lambda = len(found)

	if Lambda > 0:
		Kappa = 1
	else:
		Kappa = 0
	
	
	return (Lambda, Kappa)

def log_10(x):
	try:
		x = log10(x)
	except OverflowError:
		if x > 1:
			return inf
		return -inf
	return x
